package com.sq.partner.manager.controller;
import com.sq.partner.manager.dao.ZfbInfoDao;
import com.sq.partner.manager.service.ZfbInfoService;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/zfbController")
public class ZfbInfoController {
    @Resource
    ZfbInfoService zfbInfoService;
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(){
        return "zfbInfo/zfbBill";
    }
    @RequestMapping(value = "/index2", method = RequestMethod.GET)
    public String index2(){
        return "zfbInfo/batchAndReconciliation";
    }

    @RequestMapping(value = "/queryZfbInfo",method = RequestMethod.POST)
    @ResponseBody
    public Page queryZfbInfoByMap( Integer pageIndex, String polno,String tradeBeginTime,String tradeEndTime,String beginDate,String endDate) throws Exception{
        Page page = new Page();
        Map<String,Object> map = new HashMap<String, Object>();
        if(pageIndex != -1){
            page.setCurrent(pageIndex);
            map = SqlUtil.buildPageMap(page);
        }
        //交易日期
        if(StrUtil.isNotEmpty(tradeBeginTime)){
            tradeBeginTime = tradeBeginTime + "00:00:00";
        }
        if(StrUtil.isNotEmpty(tradeEndTime)){
            tradeEndTime = tradeEndTime + "23:59:59";
        }
        map.put("polno",polno);
        map.put("tradeBeginTime",tradeBeginTime);
        map.put("tradeEndTime",tradeEndTime);
        map.put("beginDate",beginDate);
        map.put("endDate", endDate);
        page.setType(map);
        return  zfbInfoService.queryZfbBillInfoPage(page);
    }
    //信息导出到excle表
    @RequestMapping(value = "/exportExcel")
    @ResponseBody
    public void exportExcel(HttpServletResponse response, HttpServletRequest request, String polno,String tradeBeginTime,
                            String tradeEndTime,String beginDate,String endDate) throws Exception {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("polno",polno);
        map.put("tradeBeginTime",tradeBeginTime);
        map.put("tradeEndTime",tradeEndTime);
        map.put("beginDate",beginDate);
        map.put("endDate",endDate);
        List<Map<String, Object>> zfbInfoList = zfbInfoService.queryZfbBillInfoList(map);
        String fileName = "支付宝保单查询信息表";
        String sheetName = "支付宝保单查询信息";
        // 列数
        int columnNumber = 18;
        // 列宽
        int[] columnWidth = {5, 32, 30, 32, 32, 10, 10, 20, 15, 20, 32, 10, 15, 15, 10, 15, 10,10};
        // 列名
       String[] columnName = {"序号", "商户订单号", "交易时间", "业务流水号", "保单号",  "缴费方式", "期次", "应缴含税保费金额", "手续费比例", "手续费金额", "省公司", "出单机构", "保单起期", "保单止期", "保单状态", "保单退保时间", "被保险人", "生效前/生效后"};
        // 序号
        int count = 1;
        List<String[]> tempList = new ArrayList<String[]>();
        for (Map<String, Object> zfb : zfbInfoList) {
            Double commRate= Double.parseDouble(zfb.get("COMMRATE").toString());
            Double premium= Double.parseDouble((String) zfb.get("PREMIUM"));
            DecimalFormat df = new DecimalFormat("0.00");
            String premiumStr = df.format(premium);
            Double commAmount = commRate * premium;
            String commAmountStr = df.format(commAmount);
            commRate = commRate * 100;
            String commRateStr = commRate + "%";
            if("趸交".equals((zfb.get("PAYTYPE")))){
                zfb.put("PAYNO","");
            }
            tempList.add(new String[]{String.valueOf(count++),(String)zfb.get("POLICYNO") ,(String) zfb.get("TRANSDATE"),(String) zfb.get("PAYFLOWID"),(String)(zfb.get("POLNO")),
                    (String)(zfb.get("PAYTYPE")), String.valueOf(zfb.get("PAYNO")), premiumStr,commRateStr,commAmountStr,(String) zfb.get("DEPTNAME"),
                    (String) zfb.get("DEPTCODE"), (String) zfb.get("BEGINDATE"), (String) zfb.get("ENDDATE"), (String) zfb.get("STATUS"), (String) zfb.get("VALIDDATE"),
                    (String) zfb.get("BBRNAME"), (String) zfb.get("EFFTIME"),});
        }
        // 支付宝信息的二维数组【列】【行】
        String[][] zfbInfos = tempList.toArray(new String[][]{});
        HSSFWorkbook wb = zfbInfoService.generateHssWorkBook(sheetName, columnNumber, columnWidth, columnName, zfbInfos);
        response.setContentType("application/ms-excel;charset=utf-8");
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("trident") || userAgent.contains("edge")) {
            // IE浏览器
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        OutputStream os = response.getOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            os.close();
        }
    }
 //查询退保信息
    @RequestMapping(value = "/queryZfbRefundInfo",method = RequestMethod.POST)
    @ResponseBody
    public Page queryZfbRefundInfoByMap( Integer pageIndex, String polno,String endorseNo,String tradeBeginTime,String tradeEndTime) throws Exception{
        Page page = new Page();
        Map<String,Object> map = new HashMap<String, Object>();
        if(pageIndex != -1){
            page.setCurrent(pageIndex);
            map = SqlUtil.buildPageMap(page);
        }
        //交易日期
        if(StrUtil.isNotEmpty(tradeBeginTime)){
            tradeBeginTime = tradeBeginTime + "00:00:00";
        }
        if(StrUtil.isNotEmpty(tradeEndTime)){
            tradeEndTime = tradeEndTime + "23:59:59";
        }
        map.put("polno",polno);
        map.put("endorseNo",endorseNo);
        map.put("tradeBeginTime",tradeBeginTime);
        map.put("tradeEndTime",tradeEndTime);
        page.setType(map);
        return  zfbInfoService.queryZfbRefundInfoPage(page);
    }
    //导出退保信息
    //信息导出到excle表
    @RequestMapping(value = "/exportRefundInfo")
    @ResponseBody
    public void exportRefundInfo(HttpServletResponse response, HttpServletRequest request, String polno,String endorseNo,String tradeBeginTime,
                            String tradeEndTime) throws Exception {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("polno",polno);
        map.put("endorseNo",endorseNo);
        map.put("tradeBeginTime",tradeBeginTime);
        map.put("tradeEndTime",tradeEndTime);
        List<Map<String, Object>> zfbInfoList = zfbInfoService.queryZfbRefundInfoList(map);
        String fileName = "支付宝批单查询信息表";
        String sheetName = "支付宝批单查询信息";
        // 列数
        int columnNumber = 16;
        // 列宽
        int[] columnWidth = {5, 32, 30, 32, 32, 35, 10, 20, 20, 32, 10, 10, 10, 15, 15, 15};
        // 列名
        String[] columnName = {"序号", "商户订单号", "交易时间", "业务流水号", "保单号",  "批单号","退保（含税）金额",  "手续费比例", "手续费金额", "省公司",
                "出单机构","被保人","批改生效状态","退保生效日期","保单起期","保单止期"};
        // 序号
        int count = 1;
        List<String[]> tempList = new ArrayList<String[]>();
        for (Map<String, Object> zfb : zfbInfoList) {
            BigDecimal refoundmoney = new BigDecimal(0);
            if(null != zfb.get("REFOUNDMONEY")){
                refoundmoney = new BigDecimal(zfb.get("REFOUNDMONEY").toString()).setScale(2,BigDecimal.ROUND_HALF_UP) ;
            }
            String flowNo = (String) zfb.get("PAYFLOWID");
            String refoundmoneyStr = "";
            if(null == zfb.get("REFOUNDMONEY") || "0".equals(String.valueOf(zfb.get("REFOUNDMONEY")))){
                flowNo = "";
                refoundmoneyStr = "";
            }else{
                refoundmoneyStr = "-"+refoundmoney;
            }
            tempList.add(new String[]{String.valueOf(count++),(String) zfb.get("POLICYNO"),(String) zfb.get("TRANSDATE"),flowNo,(String)(zfb.get("POLNO")),
                    (String)(zfb.get("ENDORSENO")),refoundmoneyStr,"0%","0.00",(String) zfb.get("DEPTNAME"),(String) zfb.get("DEPTCODE"),
                    (String) zfb.get("BBRNAME"), (String) zfb.get("EFFTIME"), (String) zfb.get("VALIDDATE"), (String) zfb.get("BEGINDATE"),
                    (String) zfb.get("ENDDATE"),});
        }
        // 支付宝信息的二维数组【列】【行】
        String[][] zfbInfos = tempList.toArray(new String[][]{});
        HSSFWorkbook wb = zfbInfoService.generateHssWorkBook(sheetName, columnNumber, columnWidth, columnName, zfbInfos);
        response.setContentType("application/ms-excel;charset=utf-8");
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("trident") || userAgent.contains("edge")) {
            // IE浏览器
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        OutputStream os = response.getOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            os.close();
        }
    }
}
